package cn.jinjimi.app.main.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.FileUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.domain.data.Cache;
import cn.jinjimi.app.entity.PictureShow;
import cn.jinjimi.app.main.extend.BaseActivity;
import cn.jinjimi.app.main.widget.MyProgress;
import cn.jinjimi.app.main.widget.MyViewPager;

import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
import uk.co.senab.photoview.more.ImageDownloadListener;

/**
 * Created by Roy
 * Date: 15/11/10
 */
public class PhotoBrowserActivity extends BaseActivity implements View.OnClickListener {
    List<PictureShow> pictureShowList = new ArrayList<PictureShow>();
    public int index = 0;
    private boolean canDownload;

    public MyViewPager mViewPager;
    private TextView tvPhotoNum;
    private PhotoAdapter mAdapter;

    @Override
    protected void beforeInitView() {
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏

        setContentView(R.layout.activity_normal_photo_browser_layout);
        initPictureData();
        setSwipeEnabled(false);
    }

    @Override
    protected void initial() {
        initView();
    }

    public void initPictureData() {
        pictureShowList = (List<PictureShow>) getIntent().getSerializableExtra(BundleKey.PARAM_PICTURE_SHOW);
        index = getIntent().getIntExtra(BundleKey.PARAM_START_INDEX, 0);
        canDownload = getIntent().getBooleanExtra(BundleKey.PARAM_PICTURE_CAN_DOWNLOAD, false);
    }

    protected void initView() {
        mViewPager = (MyViewPager) findViewById(R.id.view_pager);
        tvPhotoNum = (TextView) findViewById(R.id.tv_photo_guide);
        initUnderView();
        initAdapter();

        View tvDownload = findViewById(R.id.tv_download);
        tvDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoView photoView = getPhotoView();
                if (photoView != null && photoView.getDrawable() instanceof BitmapDrawable) {
                    Drawable drawable = photoView.getDrawable();
                    if (drawable instanceof BitmapDrawable) {
                        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
                        Bitmap bitmap = bitmapDrawable.getBitmap();
                        if (bitmap != null && !bitmap.isRecycled()) {
                            String path = Cache.getBrowserImageFileDictory() + System.currentTimeMillis() + ".png";
                            FileUtils.writeImage(bitmap, path, 100);
                            AndroidUtils.scanFile(PhotoBrowserActivity.this, path);
                            ToastUtils.toastMessage(PhotoBrowserActivity.this, "图片已保存到图库");
                        }
                    }
                }
            }
        });

        tvDownload.setVisibility(canDownload ? View.VISIBLE : View.GONE);
    }

    private PhotoView getPhotoView() {
        if (mAdapter.getCurrentItem() != null) {
            PhotoView photoView = (PhotoView) mAdapter.getCurrentItem().findViewById(R.id.photo_view);
            return photoView;
        }
        return null;
    }

    public void initUnderView() {
        if (pictureShowList.size() == 1) {
            tvPhotoNum.setVisibility(View.GONE);
        } else {
            tvPhotoNum.setVisibility(View.VISIBLE);
            tvPhotoNum.setText(String.format(getString(R.string.img_current_chose_num), index + 1, pictureShowList.size()));
        }
    }

    public void initAdapter() {
        mAdapter = new PhotoAdapter(this);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(index);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (pictureShowList.size() > 1) {
                    tvPhotoNum.setText(String.format(getString(R.string.img_guide_num), position + 1, pictureShowList.size()));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_download:
                break;
        }
    }

    class PhotoAdapter extends PagerAdapter {
        private Context mContext;

        private View mCurrentView;

        PhotoAdapter(Context context) {
            mContext = context;
        }

        @Override
        public int getCount() {
            return pictureShowList.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            final PictureShow pictureShow = pictureShowList.get(position);
            View cell = LayoutInflater.from(mContext).inflate(R.layout.normal_photo_browser_item_view, null);

            final PhotoView photoView = (PhotoView) cell.findViewById(R.id.photo_view);
            final MyProgress progress_bar = (MyProgress) cell.findViewById(R.id.progress_bar);
            progress_bar.setBackgroundColor(ContextCompat.getColor(PhotoBrowserActivity.this, R.color.white));
            progress_bar.setProgressColor(ContextCompat.getColor(PhotoBrowserActivity.this, R.color.blue));

            photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    finish();
                }
            });
            photoView.setImageDownloadListener(new ImageDownloadListener() {
                @Override
                public void onUpdate(int progress) {
                    if (progress >= 100) {
                        progress_bar.setVisibility(View.GONE);
                    } else {
                        progress_bar.setVisibility(View.VISIBLE);
                    }
                    progress_bar.setProgress(progress);
                }
            });
            photoView.setImageUri(pictureShow.bigUrl);

            container.addView(cell, AndroidUtils.getWindowWidth(PhotoBrowserActivity.this), AndroidUtils.getWindowHeight(PhotoBrowserActivity.this));

            return cell;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            mCurrentView = (View)object;
        }

        public View getCurrentItem() {
            return mCurrentView;
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.activity_fade_out);
    }
}
